#!/usr/bin/python
# coding=utf-8
import random, sys, logging, time, traceback
# from xpy3lib.utils.XUtils import XUtils
# from datetime import datetime
from datetime import date
from flask import Flask, request, json, jsonify, abort, make_response
import sys, datetime, json, logging, os
import pandas as pd
import numpy as np
from scipy import fftpack

from xpy3lib.utils.XDataFrameUtils import XDataFrameUtils
from xpy3lib.XRetryableQuery import XRetryableQuery

from xpy3lib.utils import db_utils as util
from xpy3lib.XLogger import XLogger
from sicost.config import app_config


app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

profile = (sys.argv[1].split("=", 1)[-1]) if len(sys.argv) > 1 else 'dev'


@app.route('/api-model/get_info.sdo', methods=["GET", "POST"])
def test_index_1():
    response_dict = {'message': 'success---hi--prm-server'}
    return json.dumps(response_dict)


@app.route('/api-model/', methods=["GET", "POST"])
def test_index_0():
    response_dict = {'message': 'success---hi--model-server'}
    return json.dumps(response_dict)


@app.route('/api-model/save_data.sdo', methods=["GET", "POST"])
def request_model():
    content = dict()
    response_dict = dict()

    body_dict = None
    if request.method == 'POST':
        try:
            try:
                request_json_text = request.get_data()
                body_dict = json.loads(request_json_text.decode('utf-8'))
            except Exception as e:
                body_dict = request.form.to_dict()
                # NOTE below is the pseudo code of post data fetching
                # postdata = request.form['id']
                # file = request.files['file']
        except Exception as e:
            body_dict = None
            traceback.print_exc()
    else:
        body_dict = request.args.to_dict(flat=True)

    #
    if body_dict is not None:
        try:
            # success, msg, remark, timestamp, table_1 = run_model_job(p_body_dict=body_dict)
            code, msg = run_model_job(p_body_dict=body_dict)
        except Exception as e:
            code = -100
            msg = f'run_model_job_failed---with--{str(body_dict)}--{str(e)}'
    else:
        code = -200
        msg = 'invalid_http_request_parameters'


    response_dict['code'] = code
    response_dict['message'] = msg
    # return json.dumps(response_dict)
    return bytes(json.dumps(response_dict), 'utf-8')
def run_model_job(p_body_dict):
    """

    """
    #程序开始
    row_data = p_body_dict
    input_dict = row_data['input']
    input_dict = eval(input_dict)
    tag = input_dict['tag']
    # path_name = str(tag) + '.json'
    path_name = '/apps/reqms/p_project/get_picture/sts_data/' + str(tag) + '.json'
    if os.path.exists(path_name):
        os.remove(path_name)
    new_output1 = json.dumps(input_dict, ensure_ascii=False)
    file = open(path_name, 'a', encoding='utf-8')
    file.write(new_output1)
    file.write('\n')
    file.close()

    code = 0
    msg = 'ok'

    return code, msg


if __name__ == '__main__':

    app.run(host='0.0.0.0', port=7079)
